package com.qf.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.pojo.R;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@Order(-5)  //控制过滤器执行的优先级，值越小，优先级越高
public class LoginFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //登录认证
//        exchange.getRequest().getHeaders() // 获取请求头
        String token = exchange.getRequest().getQueryParams().getFirst("token"); //获取请求参数

        if (token != null && token.length() != 0){
            //携带登录认证的信息，校验这个信息的合法性
            //合法 -- 放行
            //不合法 -- 阻止访问，提示给浏览器

            //放行
            return chain.filter(exchange);
        }else{
            //没有携带 -- 阻止访问
            try {
                R r = R.error().putMsg("尚未登录，请先登录");
                String json = new ObjectMapper().writeValueAsString(r);

                //利用响应对象，将这个结果提示信息写到浏览器
                ServerHttpResponse response = exchange.getResponse();
                DataBuffer wrap = response.bufferFactory().wrap(json.getBytes(StandardCharsets.UTF_8));

                //解决响应中文乱码问题
                response.getHeaders().add("content-type","application/json;charset=utf-8");

                Mono<DataBuffer> mono = Mono.just(wrap);

                return response.writeWith(mono);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
